package com.zhengxin.one.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.zhengxin.one.common.Result;
import com.zhengxin.one.entity.BillAccumulation;
import com.zhengxin.one.entity.BillBase;
import com.zhengxin.one.entity.BillCommercial;
import com.zhengxin.one.entity.BillSociety;
import com.zhengxin.one.entity.client.RecordAdd;
import com.zhengxin.one.entity.excel.AccumulationExcel;
import com.zhengxin.one.entity.excel.CommercialExcel;
import com.zhengxin.one.entity.excel.SocietyExcel;
import com.zhengxin.one.service.impl.BillServiceipml;
import com.zhengxin.one.service.impl.RecordServiceImpl;
import com.zhengxin.one.utils.FileUtil;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping(value = "shangshebao")
public class FileController {
    @Autowired
    private RecordServiceImpl recordService;
    @Autowired
    private BillServiceipml billService;
    //上传服务器
    @PostMapping("upload")
    public Result upload(@RequestParam("fileName") MultipartFile file)throws IOException{
        // 先设定一个放置上传文件的文件夹(该文件夹可以不存在，下面会判断创建)
        String filePath = "C:/Users/zx021/Desktop/file/";
        // 判断文件手否有内容
        if(file.isEmpty()){
            return Result.fail("未选择文件");
        }
        // 获取附件原名
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        int index = fileName.lastIndexOf("\\");
        if (index > 0) {
            fileName = fileName.substring(index + 1);
        }
        // 判断单个文件大于1M
        long fileSize = file.getSize();
        if (fileSize < 1024 ) {
            return Result.fail("文件必须大于1kb");
        }
        // 当文件有后缀名时
        if (fileName.indexOf(".") >= 0) {
            // split()中放正则表达式; 转义字符"\\."代表 "."
            String[] fileNameSplitArray = fileName.split("\\.");
            // 加上random戳,防止附件重名覆盖原文件
            fileName = fileNameSplitArray[0] + (int) (Math.random() * 100000) +System.currentTimeMillis()+"." + fileNameSplitArray[1];
        }
        // 当文件无后缀名时(如C盘下的hosts文件就没有后缀名)
        if (fileName.indexOf(".") < 0) {
            // 加上random戳,防止附件重名覆盖原文件
            fileName = fileName + (int) (Math.random() * 100000);
        }
        File dest = new File(filePath + fileName);
        System.out.println(dest);
        // 如果该文件的上级文件夹不存在，则创建该文件的上级文件夹及其祖辈级文件夹;
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return Result.fail("上传成功");
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.fail("上传失败");
    }
    //上传腾讯云
    @PostMapping("uploads")
    public Result uploads(@RequestParam("fileName") MultipartFile file)throws IOException {
        if(file.isEmpty()){
            return Result.fail("未选择文件");
        }
        // 获取附件原名
        String fileName = file.getOriginalFilename();
        // 当文件有后缀名时
        if (fileName.indexOf(".") >= 0) {
            // split()中放正则表达式; 转义字符"\\."代表 "."
            String[] fileNameSplitArray = fileName.split("\\.");
            // 加上random戳,防止附件重名覆盖原文件
            fileName = fileNameSplitArray[0] + (int) (Math.random() * 100000) +System.currentTimeMillis()+"." + fileNameSplitArray[1];
        }
        // 当文件无后缀名时(如C盘下的hosts文件就没有后缀名)
        if (fileName.indexOf(".") < 0) {
            // 加上random戳,防止附件重名覆盖原文件
            fileName = fileName + (int) (Math.random() * 100000)+System.currentTimeMillis();
        }
        COSCredentials cred = new BasicCOSCredentials("AKIDTq10qW982kFcWHTFgx88MUnwufEdjwqe", "qZ6RaXJyUURIbkhX7Zs7TuQsOyZ3LWVL");
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
        // 设置使用https请求
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket名需包含appid
        String bucketName = "shebao-1252715035";
        String key = "test/"+fileName;
        ObjectMetadata objectMetadata = new ObjectMetadata();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream(),objectMetadata);
        try {
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            Date expiration = new Date(new Date().getTime() + 5 * 60 * 10000);
            URL oldurl= cosclient.generatePresignedUrl(bucketName, key, expiration);
            /*String url = oldurl .toString();
            url = url.substring(0, url.indexOf("?"));*/
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("fileName",fileName);
            stringStringHashMap.put("url",oldurl.toString());
            return Result.success(stringStringHashMap);
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // 关闭客户端
        cosclient.shutdown();
        return Result.fail("上传失败");
    }
    //excel 导入
    //社保批量的预览
    @PostMapping("societyExcelShow")
    public Result soShow(@RequestParam("fileName") MultipartFile file,@RequestParam String company_id,@RequestParam String plan,@RequestParam String region) throws Exception {
        if(file.isEmpty()){
            return Result.fail("未选择文件");
        }
        //导入的标题和说明的设置
        ImportParams params = new ImportParams();
        //设置标题
        params.setTitleRows(1);
        //设置说明
        params.setHeadRows(1);
        //导入获取集合
        try{
            List<SocietyExcel> users = ExcelImportUtil.importExcel(file.getInputStream(), SocietyExcel.class, params);
            for (SocietyExcel x:users) {
                if(x.getName()==null){
                    file.getInputStream().close();
                    return Result.fail("姓名不能为空");
                }
                if(x.getId_card()==null){
                    file.getInputStream().close();
                    return Result.fail("证件号码不能为空");
                }
                if(x.getRegion()==null){
                    file.getInputStream().close();
                    return Result.fail("户籍市不能为空");
                }
                if(x.getResidence_type()==null){
                    file.getInputStream().close();
                    return Result.fail("户口性质不能为空");
                }
                if(x.getJointime()==null){
                    file.getInputStream().close();
                    return Result.fail("参保年月不能为空");
                }
                if(billService.checkS(x.getId_card())){
                    file.getInputStream().close();
                    return Result.fail("用户:"+x.getName()+","+"身份证:"+x.getId_card()+"已存在不能重复录入");
                }
            }
            HashMap<String,Object> Tmap = new HashMap<String,Object>();
            Tmap.put("excelShow",users);
            Tmap.put("plan",plan);
            Tmap.put("region",region);
            Tmap.put("company_id",company_id);
            file.getInputStream().close();
            return Result.success(Tmap);
        }catch (Exception e){
            e.printStackTrace();
            file.getInputStream().close();
            return Result.fail("excel格式不正确请下载模板并填写");
        }
    }
    //社保批量导入
    @PostMapping("societyInput")
    public Result excelIn(@RequestBody Map data) throws Exception {
        List<SocietyExcel> result =new Gson().fromJson(new Gson().toJson(data.get("excelShow")), new TypeToken<List<SocietyExcel>>(){}.getType());
        String plan = (String) data.get("plan");
        String company_id = (String) data.get("company_id");
        String region = (String) data.get("region");
        for (SocietyExcel x:result
             ) {
            //时间格式转换
            BillBase base = new BillBase();
            BillSociety society =new BillSociety();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = new Date(String.valueOf(x.getJointime()));
            String aa =sdf.format(date1);
            Date aaa = sdf.parse(aa);
            Date date2 = new Date(String.valueOf(x.getPetime()));
            String bb =sdf.format(date1);
            Date bbb = sdf.parse(aa);
            Date date3 = new Date(String.valueOf(x.getPstime()));
            String cc =sdf.format(date1);
            Date ccc = sdf.parse(aa);
            if(!billService.check(x.getId_card())){
                //添加基础信息
                base.setCompany_id(company_id);
                base.setId_card(x.getId_card());
                base.setName(x.getName());
                base.setPhone(x.getPhone());
                base.setNation(x.getNation());
                base.setResidence_type(x.getResidence_type());
                base.setRegion(x.getRegion());
                base.setSociety_id(0);
                base.setAccumulation_id(0);
                base.setCommercial_id(0);
                if(billService.insertAll(base)!=1){
                    return Result.fail("录入失败");
                }
            }
            //添加社保信息society
            society.setPlan(plan);
            society.setRegion(region);
            society.setJointime(aaa);
            society.setPetime(bbb);
            society.setPstime(ccc);
            society.setStatus(1);
            society.setPay_status(1);
            society.setCbase(x.getCbase());
            society.setBnbase(x.getBnbase());
            society.setInfo(x.getInfo());
            society.setId_card(x.getId_card());
            society.setHandle_type(1);
            billService.insertAllSociety(society);
            int bill_id = society.getId();
            //修改基础信息与之对应
            int info = billService.handbases(x.getId_card(),1,bill_id);
            if(info!=1){
                return Result.fail("添加失败");
            }
            //添加历史记录
            RecordAdd recordAdd = new RecordAdd();
            recordAdd.setId_card(x.getId_card());
            recordAdd.setCompany_id(company_id);
            recordAdd.setName(x.getName());
            recordAdd.setResidence_type(x.getResidence_type());
            recordAdd.setService_type(1);
            recordAdd.setHandle_type(1);
            recordAdd.setStatus(1);
            recordAdd.setS_region(x.getRegion());
            recordAdd.setS_cbase(x.getCbase());
            recordAdd.setS_jointime(aaa);
            recordAdd.setTtype(1);
            if(recordService.setPerson(recordAdd)!=1){
                return Result.fail("记录添加失败");
            }
        }
        return Result.success("");
    }
    //公积金预览
    @PostMapping("accumulationExcelShow")
    public Result acShow(@RequestParam("fileName") MultipartFile file,@RequestParam String company_id,@RequestParam String plan,@RequestParam String region) throws Exception {
        if(file.isEmpty()){
            return Result.fail("未选择文件");
        }
        //导入的标题和说明的设置
        ImportParams params = new ImportParams();
        //设置标题
        params.setTitleRows(1);
        //设置说明
        params.setHeadRows(1);
        //导入获取集合
        try{
            List<AccumulationExcel> users = ExcelImportUtil.importExcel(file.getInputStream(), AccumulationExcel.class, params);
            for (AccumulationExcel x:users) {
                if(x.getName()==null){
                    file.getInputStream().close();
                    return Result.fail("姓名不能为空");
                }
                if(x.getId_card()==null){
                    file.getInputStream().close();
                    return Result.fail("证件号码不能为空");
                }
                if(x.getRegion()==null){
                    file.getInputStream().close();
                    return Result.fail("户籍市不能为空");
                }
                if(x.getResidence_type()==null){
                    file.getInputStream().close();
                    return Result.fail("户口性质不能为空");
                }
                if(x.getJointime()==null){
                    file.getInputStream().close();
                    return Result.fail("参保年月不能为空");
                }
                if(billService.checkA(x.getId_card())){
                    file.getInputStream().close();
                    return Result.fail("用户:"+x.getName()+","+"身份证:"+x.getId_card()+"已存在不能重复录入");
                }
            }
            HashMap<String,Object> Tmap = new HashMap<String,Object>();
            Tmap.put("excelShow",users);
            Tmap.put("plan",plan);
            Tmap.put("region",region);
            Tmap.put("company_id",company_id);
            file.getInputStream().close();
            return Result.success(Tmap);
        }catch (Exception e){
            e.printStackTrace();
            file.getInputStream().close();
            return Result.fail("excel格式不正确请下载模板并填写");
        }
    }
    //公积金批量导入
    @PostMapping("accumulationInput")
    public Result excelIn1(@RequestBody Map data) throws Exception {
        List<AccumulationExcel> result =new Gson().fromJson(new Gson().toJson(data.get("excelShow")), new TypeToken<List<AccumulationExcel>>(){}.getType());
        String plan = (String) data.get("plan");
        String company_id = (String) data.get("company_id");
        String region = (String) data.get("region");
        for (AccumulationExcel x:result
        ) {
            //时间格式转换
            BillBase base = new BillBase();
            BillAccumulation accumulation =new BillAccumulation();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = new Date(String.valueOf(x.getJointime()));
            String aa =sdf.format(date1);
            Date aaa = sdf.parse(aa);
            Date date2 = new Date(String.valueOf(x.getPetime()));
            String bb =sdf.format(date1);
            Date bbb = sdf.parse(aa);
            Date date3 = new Date(String.valueOf(x.getPstime()));
            String cc =sdf.format(date1);
            Date ccc = sdf.parse(aa);
            if (!billService.check(x.getId_card())){
                //添加基础信息
                base.setCompany_id(company_id);
                base.setId_card(x.getId_card());
                base.setName(x.getName());
                base.setPhone(x.getPhone());
                base.setNation(x.getNation());
                base.setResidence_type(x.getResidence_type());
                base.setRegion(x.getRegion());
                base.setSociety_id(0);
                base.setAccumulation_id(0);
                base.setCommercial_id(0);
                if(billService.insertAll(base)!=1){
                    return Result.fail("录入失败");
                }
            }

            //添加公积金信息accumulation
            accumulation.setPlan(plan);
            accumulation.setRegion(region);
            accumulation.setJointime(aaa);
            accumulation.setPetime(bbb);
            accumulation.setPstime(ccc);
            accumulation.setStatus(1);
            accumulation.setPay_status(1);
            accumulation.setCbase(x.getCbase());
            accumulation.setBnbase(x.getBnbase());
            accumulation.setCompany_ratio(x.getCompany_ratio());
            accumulation.setId_card(x.getId_card());
            accumulation.setPerson_ratio(x.getPerson_ratio());
            accumulation.setHandle_type(1);
            billService.insertAllAccumulation(accumulation);
            int bill_id = accumulation.getId();
            //修改基础信息与之对应
            int info = billService.handbases(x.getId_card(),2,bill_id);
            if(info!=1){
                return Result.fail("添加失败");
            }
            //添加历史记录
            RecordAdd recordAdd = new RecordAdd();
            recordAdd.setId_card(x.getId_card());
            recordAdd.setCompany_id(company_id);
            recordAdd.setName(x.getName());
            recordAdd.setResidence_type(x.getResidence_type());
            recordAdd.setService_type(1);
            recordAdd.setHandle_type(1);
            recordAdd.setStatus(1);
            recordAdd.setA_region(x.getRegion());
            recordAdd.setA_cbase(x.getCbase());
            recordAdd.setA_e_company_ratio(x.getCompany_ratio());
            recordAdd.setA_e_person_ratio(x.getPerson_ratio());
            recordAdd.setA_jointime(aaa);
            recordAdd.setTtype(2);
            if(recordService.setPerson(recordAdd)!=1){
                return Result.fail("记录添加失败");
            }
        }
        return Result.success("");
    }
    //商保批预览
    @PostMapping("commercialExcelShow")
    public Result coShow(@RequestParam("fileName") MultipartFile file,@RequestParam String company_id,@RequestParam String plan) throws Exception {
        if(file.isEmpty()){
            return Result.fail("未选择文件");
        }
        //导入的标题和说明的设置
        ImportParams params = new ImportParams();
        //设置标题
        params.setTitleRows(1);
        //设置说明
        params.setHeadRows(1);
        //导入获取集合
        try{
            List<CommercialExcel> users = ExcelImportUtil.importExcel(file.getInputStream(), CommercialExcel.class, params);
            for (CommercialExcel x:users) {
                if(x.getName()==null){
                    file.getInputStream().close();
                    return Result.fail("姓名不能为空");
                }
                if(x.getId_card()==null){
                    file.getInputStream().close();
                    return Result.fail("证件号码不能为空");
                }
                if(x.getRegion()==null){
                    file.getInputStream().close();
                    return Result.fail("户籍市不能为空");
                }
                if(x.getResidence_type()==null){
                    file.getInputStream().close();
                    return Result.fail("户口性质不能为空");
                }
                if(x.getJointime()==null){
                    file.getInputStream().close();
                    return Result.fail("参保年月不能为空");
                }
                if(billService.checkC(x.getId_card())){
                    file.getInputStream().close();
                    return Result.fail("用户:"+x.getName()+","+"身份证:"+x.getId_card()+"已存在不能重复录入");
                }
            }
            HashMap<String,Object> Tmap = new HashMap<String,Object>();
            Tmap.put("excelShow",users);
            Tmap.put("plan",plan);
            Tmap.put("company_id",company_id);
            file.getInputStream().close();
            return Result.success(Tmap);
        }catch (Exception e){
            e.printStackTrace();
            file.getInputStream().close();
            return Result.fail("excel格式不正确请下载模板并填写");
        }
    }
    //商保批量导入
    @PostMapping("commercialInput")
    public Result excelIn2(@RequestBody Map data) throws Exception {
        List<CommercialExcel> result =new Gson().fromJson(new Gson().toJson(data.get("excelShow")), new TypeToken<List<CommercialExcel>>(){}.getType());
        String plan = (String) data.get("plan");
        String company_id = (String) data.get("company_id");
        for (CommercialExcel x:result
        ) {
            //时间格式转换
            BillBase base = new BillBase();
            BillCommercial commercial =new BillCommercial();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = new Date(String.valueOf(x.getJointime()));
            String aa =sdf.format(date1);
            Date aaa = sdf.parse(aa);
            if (!billService.check(x.getId_card())){
                //添加基础信息
                base.setCompany_id(company_id);
                base.setId_card(x.getId_card());
                base.setName(x.getName());
                base.setPhone(x.getPhone());
                base.setNation(x.getNation());
                base.setResidence_type(x.getResidence_type());
                base.setRegion(x.getRegion());
                base.setSociety_id(0);
                base.setAccumulation_id(0);
                base.setCommercial_id(0);
                if(billService.insertAll(base)!=1){
                    return Result.fail("录入失败");
                }
            }
            //添加商保信息
            commercial.setPlan(plan);
            commercial.setJointime(aaa);
            commercial.setStatus(1);
            commercial.setPay_status(1);
            commercial.setId_card(x.getId_card());
            commercial.setHandle_type(1);
            billService.insertAllCommercia(commercial);
            int bill_id = commercial.getId();
            //修改基础信息与之对应
            int info = billService.handbases(x.getId_card(),3,bill_id);
            if(info!=1){
                return Result.fail("添加失败");
            }
            //添加历史记录
            RecordAdd recordAdd = new RecordAdd();
            recordAdd.setId_card(x.getId_card());
            recordAdd.setCompany_id(company_id);
            recordAdd.setName(x.getName());
            recordAdd.setResidence_type(x.getResidence_type());
            recordAdd.setService_type(1);
            recordAdd.setHandle_type(1);
            recordAdd.setStatus(1);
            recordAdd.setC_plan(plan);
            recordAdd.setTtype(3);
            if(recordService.setPerson(recordAdd)!=1){
                return Result.fail("记录添加失败");
            }
        }
        return Result.success("");
    }
    //下载文件
    @RequestMapping(value = "download")
    public void download(@RequestParam("fileName") String filename) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 设置信息给客户端不解析
        String type = new MimetypesFileTypeMap().getContentType(filename);
        // 设置contenttype，即告诉客户端所发送的数据属于什么类型
        response.setHeader("Content-type",type);
        // 设置编码
        String hehe = new String(filename.getBytes("utf-8"), "iso-8859-1");
        // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
        response.setHeader("Content-Disposition", "attachment;filename=" + hehe);
        FileUtil.download(filename, response);
    }
}
